﻿using System;
using System.Configuration;
using System.Text;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.IO;
using System.Runtime;
using System.Reflection;
using System.Xml;
using System.Timers;
using AutoResumeSend.Entity;

namespace AutoResumeSend.Componments
{
    public class LogHelper
    {
        private static Timer time = new Timer();

        public static System.Text.Encoding encoding = System.Text.Encoding.Default;

        private static object sysObject = new object();

        static DateTime createFileTime = DateTime.Now;
        static DateTime flushTime = DateTime.Now;
        static DateTime flushSingleTime = DateTime.Now;

        static FileStream fsTime = null;
        static StreamWriter writerTime = null;

        static FileStream fs = null;
        static StreamWriter writer = null;

        static FileStream fsError = null;
        static StreamWriter writerError = null;


        static LogHelper()
        {
            time.Enabled = true;
            // time.AutoReset = true;
            time.Interval = 3 * 1000;
            time.Elapsed += new ElapsedEventHandler(TimerEvent);
            time.Start();
        }

        private static void TimerEvent(object sender, System.Timers.ElapsedEventArgs args)
        {

            if (writerTime != null)
            {
                writerTime.Flush();
            }

            if (writer != null)
            {
                writer.Flush();
            }



        }


        public static string GetRandomFileName(string FileName)
        {

            string fileName = FileName + "_" + DateTime.Now.ToShortDateString();

            fileName += ".log";
            return fileName;
        }

        public static void WriteFormat(string msg, params object[] para)
        {
            WriteLine(string.Format(msg, para));
        }

        public static void LogException(Exception e)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(e.Message);
            sb.AppendLine(e.GetType().ToString());
            sb.AppendLine(e.StackTrace);

            Exception baseEx = e.GetBaseException();
            if (baseEx != null)
            {
                sb.AppendLine("-----base exception----");
                sb.AppendLine(baseEx.Message);
                sb.AppendLine(baseEx.GetType().ToString());
                sb.AppendLine(baseEx.StackTrace);

            }

            LogError(sb.ToString());


        }

        public static void LogError(string msg)
        {
            string strData = System.DateTime.Now.ToString() + "	" + msg;

            try
            {
                CreateFile();

                writerError.WriteLine(strData);
                writerError.Flush();

                writer.WriteLine(strData);
                writer.Flush();
            }
            catch (Exception e)
            {

                //throw e;
            }
        }

        public static void WriteSingleLine(string msg)
        {
            string strData = System.DateTime.Now.ToString() + "	" + msg;

            try
            {
                CreateFile();

                writerTime.WriteLine(strData);
                TimeSpan ts = DateTime.Now.Subtract(flushSingleTime);
                if (ts.TotalSeconds > 3)
                {

                    writerTime.Flush();
                    flushSingleTime = DateTime.Now;
                }
            }
            catch (Exception e)
            {

                //throw e;
            }

        }

        public static void WriteLine(string msg)
        {
            string strData = System.DateTime.Now.ToString() + "	" + msg;

            try
            {
                CreateFile();


                writer.WriteLine(strData);
                TimeSpan ts = DateTime.Now.Subtract(flushTime);
                if (ts.TotalSeconds > 5)
                {
                    writer.Flush();
                    flushTime = DateTime.Now;
                }
            }
            catch (Exception e)
            {

                //throw e;
            }

        }

        public static void Close()
        {
            time.Stop();
            time.Enabled = false;

            if (fs != null)
                fs.Close();

            if (fsTime != null)
                fsTime.Close();

            if (fsError != null)
                fsError.Close();


        }

        private static void CreateFile()
        {
            if (fs == null || createFileTime.Day != DateTime.Now.Day)
            {
                lock (sysObject)
                {
                    if (fs == null || createFileTime.Day != DateTime.Now.Day)
                    {
                        string path = Config.LogFileName;


                        if (string.IsNullOrEmpty(path))
                        {
                            path = @"c:\UserStep.txt";
                            //   pathTime = @"d:\UserSteptime.txt";
                        }

                        string filePathName = GetRandomFileName(path);
                        string filePathTime = GetRandomFileName(path.Replace(".", "_list."));

                        string erorrPath = GetRandomFileName(path.Replace(".", "_error."));

                        if (fs != null)
                            fs.Close();

                        if (fsTime != null)
                            fsTime.Close();

                        if (fsError != null)
                            fsError.Close();

                        fs = new FileStream(filePathName, FileMode.Append, FileAccess.Write);
                        writer = new StreamWriter(fs, encoding);

                        fsTime = new FileStream(filePathTime, FileMode.Append, FileAccess.Write);
                        writerTime = new StreamWriter(fsTime);

                        fsError = new FileStream(erorrPath, FileMode.Append, FileAccess.Write);
                        writerError = new StreamWriter(fsError);

                        createFileTime = DateTime.Now;
                    }
                }
            }
        }
    }
}
